﻿<html>
 <head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="leaflet/leaflet.css" />
  <script src="leaflet/leaflet.js"></script>
  <style>
body {
    font-family:sans-serif
}
.ui_box {
    border-color:gray;
    border-style:solid;
    border-width:1px;
    overflow-y: scroll;
}
.text_but {
    width: 100%;
    min-width: 100%;
    cursor: pointer;
}
.text_but:hover {
    background-color: #E0E0F0;
}
.value {
    background-color: #F0F0FF;
}
.roundrect_button {
    border-color:gray;
    border-style:solid;
    border-width:1px;
    padding-left: 5px;
    padding-right: 5px;
    padding-top: 1px;
    padding-bottom: 1px;
    border-radius: 5px;
}
.roundrect_button.disabled {
    color: gray;
}
.roundrect_button:not(.disabled):hover {
    background-color: #E0E0F0;
}
.points_list {
    margin: 0px 0px 0px 0px;
}
  </style>
  <script>
var map
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
var osmCopy='Map data &copy; OpenStreetMap contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'
var latbox
var lngbox
var points = []
var layers = {}
var current_layer = ""
var current_item = -1
var current_marker = null
var unsaved_changes = {}
var notlogged_reported = false
var ui_panels = {empty: {hide:hide_empty},
                 layer: {show: show_layer, hide: hide_layer},
                 edit_point: {show: show_edit_point, hide: hide_edit_point}}
var cur_ui_panel = "empty"

//Utils
function elem(x) {
    return document.getElementById(x)
}
function attr(e,att) {
    return e.attributes.getNamedItem(att).value
}
function set_sizes() {  
    mapdiv_height = Math.floor(0.9*window.innerHeight)
    elem("mapdiv").style.height = mapdiv_height
    elem("layer_list_container").style.height = 0.3*mapdiv_height
    up = elem("layer_items").getBoundingClientRect().top
    upload_rect = elem("upload_button").getBoundingClientRect()
    bottom = mapdiv_height-(upload_rect.bottom-upload_rect.top)
    elem("layer_items").style.height = bottom-up-20;
}

//UI show/hide
function hide_empty() {
    elem("empty_ui").style.display="none"
}
function show_layer() {
    var i
    var html     
    layer = layers[current_layer]
    html = "<table>"
    html += "<tr><td>שם (עברית):</td><td class='value'>"+layer.name_he+"</td></tr>"
    html += "<tr><td>שם (אנגלית):</td><td class='value'>"+layer.name_en+"</td></tr>"
    if (layer.displayed) 
        html += "<tr><td>תצוגה:</td><td class='value'>שכבה זו מוצגת למשתמש</td></tr>"
    else
        html += "<tr><td>תצוגה:</td><td class='value'>שכבה זו איננה מוצגת,<br> אולם ניתן לחפש בה</td></tr>"
    html += "</table>"
    elem("layer_properties").innerHTML = html
    html = "<div class='text_but' onclick='add_item()'>"
    html += "<b><span style='color:#00C000;padding:2px'>+</span> הוספת נקודה חדשה</b></div>"
    html += "<ol class='points_list'>"
    for (i=0;i < layer.items.length;i++) {
        item = layer.items[i]
        display_name = item.name_he+" ("+item.name_en+")"
        //html += "<hr>"
        html += "<li><div class='text_but' onclick='edit_item("+i+")'>"+display_name+"</div></li>"
        
    }
    html += "</ol>"
    elem("layer_items").innerHTML = html
    elem("layer_ui").style.display="block"
    set_sizes()
}
function hide_layer() {
    elem("layer_ui").style.display="none"
}
function show_edit_point() {
    elem("descrbox_he").value = ""
    elem("descrbox_en").value = ""
    if (current_item == -1) {
        elem("location").innerHTML = "לא נבחר מיקום"
        elem("namebox_he").value = ""
        elem("namebox_en").value = ""
        elem("delete_button").style.display="none"
    } else {
        item = layers[current_layer].items[current_item]
        set_position(item.lat,item.lng)
        elem("namebox_he").value = item.name_he
        elem("namebox_en").value = item.name_en
        if (item.hasOwnProperty("descr_he") && item.descr_he.trim() != "")
            elem("descrbox_he").value = item.descr_he
        if (item.hasOwnProperty("descr_en") && item.descr_en.trim() != "")
            elem("descrbox_en").value = item.descr_en
        elem("delete_button").style.display="inline"
    }
    elem("edit_point_ui").style.display="block"
} 
function hide_edit_point() {
    if (current_marker != null) {
        map.removeLayer(current_marker)
        current_marker = null
    }
    elem("edit_point_ui").style.display="none"
}
function set_ui(name) {
    ui_panels[cur_ui_panel].hide()
    ui_panels[name].show()
    cur_ui_panel = name
}

//Comms
//string = "POST /?name=gates HTTP/1.1\r\nHost: tau-map.appspot.com\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 3214\r\n\r\n"+cont+"\r\n"
function load_layers() {
    request = new XMLHttpRequest()
    request.open("GET","http://tau-map.appspot.com/?name=config")
    request.onreadystatechange=function() {
        var i
        if (request.readyState == 4) {
            if (request.status != 200) {
                alert("שגיאה בטעינת רשימת השכבות")
                return
            }
            elem("layer_list").innerHTML="טוען קבצי שכבה..."
            config = request.responseText
            entries = config.trim().split(" ")
            for (i=0;i < entries.length;i++) {
                var name = entries[i].split(":")[0]
                load_layer_file(name)
            }
        }
    }
    request.send()
}

function load_layer_file(name) {
    var request = new XMLHttpRequest()
    request.open("GET","http://tau-map.appspot.com/?name="+name)
    request.onreadystatechange=function() {
        var i
        var ch
        console.log(request.readyState+" "+name+" "+layers[name])
        if (this.readyState == 4) {
            var parser = new DOMParser()
            var text = this.responseText
            var xml = parser.parseFromString(text,"text/xml")
            var xml_items = xml.getElementsByTagName("item")
            var layer = {}
            var root = xml.getElementsByTagName("layer")[0]
            layer.items = []
            layer.name_he = attr(root,"he")
            layer.name_en = attr(root,"en")
            layer.image = xml.getElementsByTagName("image_name")[0].childNodes[0].nodeValue.trim()
            layer.displayed = (attr(root,"display").toLowerCase() == "true")
            for (i=0;i < xml_items.length;i++) {
                var children = xml_items[i].childNodes
                var item = {name_he:"",name_en:"",lat:0.0,lng:0.0}
                for (ch=0;ch < children.length;ch++) {
                    var child = children[ch]
                    if (child.nodeName == "name") {
                        item.name_he = attr(child,"he")
                        item.name_en = attr(child,"en")
                    }
                    if (child.nodeName == "node") {
                        item.lat = parseFloat(attr(child,"lat"))
                        item.lng = parseFloat(attr(child,"lon"))
                    }
                    if (child.nodeName == "descr") {
                        var text = child.childNodes[0].nodeValue
                        if (attr(child,"lang") == "he")
                            item.descr_he = text
                        if (attr(child,"lang") == "en")
                            item.descr_en = text
                    }
                }
                layer.items.push(item)
            }
            layers[name]=layer
            show_layer_list()
        }
    }
    request.send()
}

function init() {
    set_sizes()
    load_layers()
    latbox = document.getElementById("lat")
    lngbox = document.getElementById("lng")
    descrbox = document.getElementById("descr")
    map = L.map('mapdiv')
    base = L.tileLayer(osmUrl, {
            attribution: osmCopy,
            maxZoom: 18, minZoom: 15})
    map.setMaxBounds([[32.102,34.795],[32.119,34.808]])
    map.fitBounds([[32.106,34.800],[32.118,34.808]])
    base.addTo(map)
    map.on('click', map_click)
}
function switch_layer(filename) {
    current_layer = filename
    set_ui("layer")
}
function show_layer_list() {
    var i
    var html = ""
    for (var name in layers) {
        layer = layers[name]
        if (!layer.hasOwnProperty("items"))
            continue
        html += "<div class='text_but' onclick='javascript:switch_layer(\""+name+"\")'>"
        html += layer.name_he+" ("+layer.name_en+")"
        html += "</div>"
    }
    elem("layer_list").innerHTML = html
}
function add_item() {
    set_ui("edit_point")
}
function edit_item(i) {
    current_item = i
    set_ui("edit_point")
}
function accept_edit() {
    if (current_marker == null) {
        alert("שגיאה: לא נבחר מיקום")
        return
    }
    item = {}
    item.lat = current_marker.getLatLng().lat
    item.lng = current_marker.getLatLng().lng
    item.name_he = elem("namebox_he").value
    item.name_en = elem("namebox_en").value
    descr = elem("descrbox_he").value
    if (descr.trim() != "")
        item.descr_he = descr
    descr = elem("descrbox_en").value
    if (descr.trim() != "")
        item.descr_en = descr
    if (current_item == -1)
        layers[current_layer].items.push(item)
    else
        layers[current_layer].items[current_item] = item
    mark_changed()
    set_ui("layer")
}
function delete_point() {
    layers[current_layer].items.splice(current_item,1)
    mark_changed()
    set_ui("layer")
}
function set_position(lat,lng) {
    if (current_marker == null) {
        current_marker = L.marker([lat,lng])
        current_marker.addTo(map)
    } else
        current_marker.setLatLng(L.latLng(lat,lng))
    elem("location").innerHTML = (""+lat).substring(0,8)+","+(""+lng).substring(0,8)
}
function map_click(e) {
    set_position(e.latlng.lat,e.latlng.lng)
}
function mark_changed() {
    unsaved_changes[current_layer]=true
    elem("upload_button").className = "roundrect_button"
}
function xml_for_descr(lang,text) {
    var xml = "\t\t<descr lang=\""+lang+"\">\n"
    xml += xml_encode(text.trim())+"\n"
    xml += "\t\t</descr>\n"
    return xml
}

function xml_encode(value) {
    return value.replace(/&/g, '&amp;')
               .replace(/</g, '&lt;')
               .replace(/>/g, '&gt;')
               .replace(/"/g, '&quot;')
               .replace(/'/g, '&apos;')
}

function xml_for_layer(name,vers) {
    var i
    var layer = layers[name]
    var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    xml += "<layer he=\""+xml_encode(layer.name_he)+"\" en=\""+xml_encode(layer.name_en)+"\" display=\""
    if (layer.displayed)
        xml += "true"
    else
        xml += "false"
    xml += "\" version=\""+vers+"\">\n"
    xml += "\t<image_name>\n"
    xml += "\t\t"+layer.image+"\n"
    xml += "\t</image_name>\n"
    for (i=0;i < layer.items.length;i++) {
        item = layer.items[i]
        xml += "\t<item>\n"
        xml += "\t\t<name he=\""+xml_encode(item.name_he)+"\""
        xml += " en=\""+xml_encode(item.name_en)+"\" />\n"
        xml += "\t\t<node lat=\""+item.lat+"\""
        xml += " lon=\""+item.lng+"\" />\n"
        if (item.hasOwnProperty("descr_he") && item.descr_he.trim() != "")
            xml += xml_for_descr("he",item.descr_he)
        if (item.hasOwnProperty("descr_en") && item.descr_en.trim() != "")
            xml += xml_for_descr("en",item.descr_en)
        xml += "\t</item>\n"
    }
    xml += "</layer>"
    return xml
}

function send_layer(name) {
    version = ""+Math.floor(Math.random()*1000000000)
    xml = xml_for_layer(name,version)
    request = new XMLHttpRequest()
    request.open("POST","http://tau-map.appspot.com/?name="+name+"&version="+version)
    request.onreadystatechange=function() {
        if (request.readyState == 4) {
            if (request.status == 401 && (!notlogged_reported)) {
                alert("שגיאה בהעלאת השינויים לשכבה "+name+": אינך מחובר/ת")
                notlogged_reported = true
                elem("upload_button").innerHTML = "העלאת שינויים לשרת"
                return
            }
            if (request.status != 200) {
                alert("שגיאה בהעלאת השינויים לשכבה "+name)
                return
            }
            delete unsaved_changes[name]
            changed_layers = Object.keys(unsaved_changes)
            if (changed_layers.length == 0) {
                alert("השינויים הועלו בהצלחה.")
                elem("upload_button").innerHTML = "העלאת שינויים לשרת"
                elem("upload_button").className = "roundrect_button disabled"
            }
        }
    }
    request.send(xml)
}
function upload_changes() {
    var i
    changed_layers = Object.keys(unsaved_changes)
    if (changed_layers.length == 0)
        return
    ok=confirm("בוצעו שינויים בשכבות הבאות:"+changed_layers.join()+"\nהאם להעלות לשרת?")
    if (!ok)
        return;
    notlogged_reported = false
    for (i=0;i < changed_layers.length;i++)
         send_layer(changed_layers[i])
    elem("upload_button").innerHTML = "מעלה שינויים..."
}

  </script>
 </head>
 <body onload="init()">
  <table width="100%">
   <tr>
    <td width="70%" rowspan="2">
     <div id="mapdiv" style="width:100%"></div>
    </td>
    <td id="right_panel" dir="rtl" style="vertical-align:super">
     <div id="layer_list_container" dir="rtl">
      <div style="text-align:left">
       <a href="/?logout=true">התנתק</a>
      </div>
      <b>שכבות:</b>
      <div id="layer_list">   
       טוען רשימת שכבות...
      </div>
     </div>
     <hr />
     <div dir="rtl" style="position:relative;bottom:0">
      <div id="empty_ui">
       <span style="color:gray">לא נבחרה שכבה</span>
      </div>
      <div id="layer_ui" style="display:none">
       <b>מאפייני שכבה:</b>
       <div id="layer_properties"></div>
       <br />
       <b>מקומות:</b>
       <div class="ui_box" id="layer_items"></div>
       <br />
       <div style="text-align:center">
        <span class="roundrect_button disabled" id="upload_button" onclick="upload_changes()">
         העלאת שינויים לשרת
        </span>
       </div>
      </div>
      <div id="edit_point_ui" style="display:none">
       מקום: <span id="location" style="color:gray">לא נבחר מקום</span><br />
       שם (עברית): <input type="text" id="namebox_he" /><br />
       שם (אנגלית): <input type="text" id="namebox_en" /><br />
       מידע נוסף (עברית): <br />
       <textarea id="descrbox_he" style="height:150"></textarea><br />
       מידע נוסף (אנגלית): <br />
       <textarea id="descrbox_en" style="height:150"></textarea><br />
       <span id="delete_button" style="display:none">
        <input type="button" value="מחיקת מקום" onclick="delete_point()" />
       </span>
       <input type="button" value="אישור" onclick="accept_edit()" />
       <input type="button" value="חזור" onclick='set_ui("layer")' />
      </div>
     </div>
    </td>
   </tr>
  </table>
 </body>
</html>
